package de.hsb.ai.agent.misterstar;

import game.Move;
import i18n.I18n;

import java.awt.Point;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.StringTokenizer;

import javax.swing.JOptionPane;

import de.hsb.ai.util.map.ScotlandJadeMapHelper.ScotlandJadeVertex;

public class MisterStarHelper {
	private int nodesCount;
	private Point[] nodePositions;	
	
	public MisterStarHelper() {
		readPosFile();
	}
	
	public Point[] getNodePositions() {
		return nodePositions;
	}
	
	public int getNodesCount() {
		return nodesCount;
	}
	
	public double getDistance(int from, int to)
	{
		Point f = nodePositions[from];
		Point t	= nodePositions[to];
				
		return Math.sqrt(Math.pow((f.x - t.x),2) + Math.pow((f.y - t.y),2));
	}
	
	public Point getPosition(ScotlandJadeVertex vertex)
	{
		return getPosition(vertex.getIndex());
	}
	
	public Point getPosition(Move move)
	{
		return getPosition(move.getNode());
	}
	
	public Point getPosition(int index)
	{
		return nodePositions[index];
	}
	
	private void readPosFile() {
		String resource = "SCOTPOS.TXT";
		URL url = getClass().getClassLoader().getResource(resource);
		try {
			InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(resource);
			InputStreamReader inputStreamReader = new InputStreamReader(resourceAsStream);
			BufferedReader map = new BufferedReader(inputStreamReader);
			String buffer = map.readLine();
			StringTokenizer token = new StringTokenizer(buffer);
			nodesCount = Integer.parseInt(token.nextToken());
			nodePositions = new Point[nodesCount];

			for (int i = 0; i < nodesCount; i++) {
				buffer = map.readLine();
				token = new StringTokenizer(buffer);
				int node = Integer.parseInt(token.nextToken());
				int x = Integer.parseInt(token.nextToken());
				int y = Integer.parseInt(token.nextToken());

				nodePositions[node] = new Point(x, y);
			}
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, I18n.tr("ErrorFileNotFound", url), 
					I18n.tr("ErrorTitle"), JOptionPane.ERROR_MESSAGE);
			System.exit(1);
		}
	}
}
